import httpRequest from "@/utils/http";
import { Result } from "@/utils/result";

// 从精选歌单中挑选歌曲
const getSongByTopPlaylist = async (ctx, next) => {
    // 1. 获取精选歌单列表
    // const result = await axios.get('http://localhost:3000').data
    const { data: result } = await httpRequest.get<any, any, any>({
        baseURL: "http://139.224.239.6:3456/top/playlist/highquality?limit=10"
    });

    // 2. 随机获取歌单 id
    const { playlists } = result;
    const playlist = playlists[Math.floor(Math.random() * 10)];
    const playListId = playlist.id ? playlist.id : 3233164347;

    // 3. 获取歌单中歌曲列表，并随机获取歌曲id
    const { trackCount } = playlist;
    const limitNum = trackCount > 20 ? 20 : 5;

    const { resData, msg } = await getSongByPlaylist(playListId, limitNum);

    ctx.resData = resData;
    ctx.msg = msg;

    await next();
};

// 从热播榜中挑选歌曲
// 热歌榜也是歌单的一种，因此逻辑上和从歌单中挑选不同的仅仅只是歌单id固定为热歌榜

// 从歌单中随机挑选歌曲
const getSongByPlaylist = async (playlistId, limitNum) => {
    const result = await httpRequest.get<any, any, any>({
        baseURL: `http://139.224.239.6:3456/playlist/track/all?id=${playlistId}&limit=${limitNum}`
    });

    const { songs } = result;

    const song = songs[Math.floor(Math.random() * limitNum)];

    const songId = song.id ? song.id : 33894312;

    const songInfo = { id: songId, url: "", name: song.name, author: song.ar, album: song.al };
    // const songId = songList.songs[0].id

    // 4. 检查版权并获取播放地址（会员歌曲正常响应30s试听链接)
    // const { data: checkResult } = await axios.get(`http://139.224.239.6:3456/check/music?id=${songId}`);
    const checkResult = await httpRequest.get<any, any, any>({
        baseURL: `http://139.224.239.6:3456/check/music?id=${songId}`
    });

    let resData = {};
    let msg = "";
    if (checkResult.success) {
        // 5. 获取播放信息
        const songPlayInfo = await httpRequest.get<any, any, any>({
            baseURL: `http://139.224.239.6:3456/song/url/v1?id=${songId}&level=standard`
        });
        songInfo.url = songPlayInfo.data[0].url;
        resData = songInfo;
        msg = "success";
    } else {
        // await getSongByTopPlaylist()
        resData = songInfo;
        msg = "无版权";
    }

    return { resData, msg };
};
const getSongByHotTopList = async (ctx, next) => {
    const Hot_Top_List_Id = 3778678;

    const { resData, msg } = await getSongByPlaylist(Hot_Top_List_Id, 50);

    Result.ok(ctx, resData, msg);
};

export { getSongByTopPlaylist, getSongByHotTopList };
